import {BaseApi} from "./BaseApi.ts";
import {buildItemDataBody, buildItemTypeInfo, ItemType} from "../types/Item.ts";

export class ItemApi extends BaseApi {
    info = (types: number[]) => this.instance.get("nuke.php", {
        params: {
            types: types.join(","),
            func: "item",
            act: "info",
            __output: 8,
        },
    }).then(res => {
        const json = res.data.data
        return Object.keys(json).map(key => buildItemTypeInfo(key, json[key]))
    })

    infoByType = (type: number, subType: number[]) => {
        const types: number[] = []
        subType.forEach(i => {
            types.push(type)
            types.push(i)
        })
        return this.info(types)
    }
    // 查询道具商店库存
    store = (page?: number | undefined, type?: ItemType | undefined, subType?: number[] | undefined) => this.postNuke({
        act: "store",
        type,
        page,
        sub_type: subType?.join(","),
    }).then(r => buildItemDataBody(r))
    // 查询道具仓库
    inventory = (page?: number | undefined) => this.postNuke({act: "list", page,}).then(r => buildItemDataBody(r))
    /**
     * 使用道具
     * @param id 根据使用的道具是库存中的还是商店中的，取对应ID
     * @param act 使用库存中的道具， 或购买商店中的道具并使用
     * @param arg 参数，对用户使用时传用户ID，对回复使用时传 [主题ID, 回复ID] 数组
     *
     */
    use = (id: number, act: "use" | "buy_and_use", arg: number | number[]) => {
        // 如果arg 为数字，则直接传递
        if (typeof arg === "number") return this.postNuke({id, act, arg});
        // 如果arg 为数组，则用 \t 连接为字符串
        return this.postNuke({id, act, arg: [...arg, 0].join("\t")});
    }
    // 购买（暂仅限于徽章）
    buy = (id: number) => this.postNuke({id, act: "buy", count: 1})

    postNuke = (params: any) => this.instance.post("nuke.php", {
        ...params,
        __output: 8,
        func: "item",
    }).then(res => res.data.data)
}